<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
// 引入Validator 
use Illuminate\Support\Facades\Validator;
// 支付模型
use App\Models\Pay\Pay as PayModel;
// 账号模型
use App\Models\Business\Business as BusinessModel;
// 配置模型
use App\Models\Config as ConfigModel;
// 消费记录模型
use App\Models\Business\Record as RecordModel;
use Illuminate\Support\Facades\DB;

class Pay extends Controller
{
    public function pay()
    {
        $money = request('money', 0);
        $paytype = request('paytype', 0);
        $busid = request("busid", 0);
        $money = floatval($money);
        if ($money < 0) {
            $this->error('充值金额不能小于1元');
        }
        $businessinfo = BusinessModel::find($busid)->toArray();
        if (!$businessinfo) {
            return error('用户不存在');
        }
        // 用户ID
        $third = json_encode(['busid' => $busid]);
        // Env 获取env文件路面的，没有再获取数据库里的 获取当前站点域名
        $urls = ConfigModel::where('name', 'url')->value('value');
        $url = env('SITES_URL', $urls);
        $OrderUrl = $url . '/pay/index/create';
        $wxcode = $url . ConfigModel::where('name', 'wxcode')->value('value');
        $zfbcode = $url . ConfigModel::where('name', 'zfbcode')->value('value');
        $data = [
            'name' => '余额充值',
            'third' => $third,
            'paytype' => $paytype,
            'originalprice' => $money,
            'paypage' => 0, // 0 json 1 收银页面,
            'reurl' => 'http://jie.laravelshop.jied.top/shop/pay/notice',
            'callbackurl' => 'http://jie.laravelshop.jied.top/shop/pay/callback',
            'status' => '0',
            'wxcode' => $wxcode,
            'zfbcode' => $zfbcode,
        ];
        $result = httpRequest($OrderUrl, $data, 1);
        echo $result;
        exit;
    }
    // 充值成功回调函数
    public function callback()
    {
        $params = request()->all();
        $price = isset($params['price']) ? $params['price'] : 0;
        $third = isset($params['third']) ? $params['third'] : '';
        
        // json字符串($third,true) true 转换数组 默认对象
        if($third){
            $third = json_decode($third, true);
        }
        $busid = isset($third['busid']) ? $third['busid'] : 0;
        
        $paytype = isset($params['paytype']) ? $params['paytype'] : 0;
        // 支付订单id
        $payid = isset($params['id']) ? $params['id'] : 0;
        
        $pay = PayModel::find($payid);
       
        if (!$pay) {
            return error('订单不存在');
        }
        
        // 充值类型转换
        $payment = '';
        switch ($paytype) {
            case 0:
                $payment = "微信支付";
                break;
            case 1:
                $payment = "支付宝支付";
                break;
        }
       
        // 判断充值金额
        if ($price <= 0) {
            return error("充值金额为0");
        }
        $business = BusinessModel::find($busid);
        
        if (!$business) {
            return error("充值用户不存在");
        }
        // 开启事务
        DB::beginTransaction();
        try {
            $updateMoney = floatval(bcadd($price, $business['money'], 2));
            // 封装用户更新的数据
            $BusinessData = [
                'money' =>$updateMoney,
            ];
            // 封装订单添加的数据
            $RecordData = [
                'total' => $price,
                'content' => "{$payment}充值了{$price}元",
                'busid' => $busid,
                'state' => '3'
            ];
            // 用户校验器
            $rule = [
                'money' => ['numeric','min:0.01']
            ];
            // 错误提示信息
            $message = [
                'money.numeric' => '余额数据类型',
                'money.min' => '余额必须大于0元'
            ];
            
            $validator = Validator::make($BusinessData, $rule, $message);
            if ($validator->fails()) {
                return error($validator->errors()->first());
            }
            // 消费记录校验器
            $rule2 = [
                'total' => ['required'],
                'content' => ['required'],
                'busid' => ['required'],
                'state' => ['required']
            ];

            // 错误提示信息
            $message2 = [
                'total.required' => '消费金额必填',
                'content.required' => '消费描述必填',
                'busid.required' => '用户id必填',
                'state.required' => '状态消费积分必填',
            ];
            // 校验器
            $validator2 = Validator::make($RecordData, $rule2, $message2);
            if ($validator2->fails()) {
                return error($validator2->errors()->first());
            }
          
            // 用户余额更新
            BusinessModel::where('id', $busid)->update($BusinessData);
          
            // 添加消费记录
            RecordModel::create($RecordData);
            DB::commit();
            return success('支付成功');
        } catch (\Exception $ex) {
            DB::rollBack();
            return error('支付失败');
        }
    }
    //  充值完成后跳转的网页
    public function notice()
    {
        return success('购买商品成功', '/business/paylist');
    }
    // 充值记录
    public function paylist(){
        $busid = request('busid', 0);
        $num=(int)request('num',1);
        $business = BusinessModel::find($busid);
        if (!$business) {
            return error('用户不存在');
        }
         // 用户ID
         $third = json_encode(['busid' => $busid]);
         $count=PayModel::where(['third'=> $third,'name'=>'余额充值'])->count();
         if($count==0){
            return error('暂无消费记录');
        }
        $list = PayModel::where(['third'=> $third,'name'=>'余额充值'])->orderBy('id', 'desc')->paginate(5,["*"],'page',$num)->toArray();
        return success('获取成功',['record'=>$list['data'],'count'=>$count]);
    }
    
}
